package com.oocl.ha.merchant.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message; 
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.oocl.ha.entity.Dish;
import com.oocl.ha.entity.Merchant;
import com.oocl.ha.merchant.service.DishManager;
import com.oocl.ha.merchant.util.ConfigUtil;
import com.oocl.ha.merchant.util.UploadImgUtil;
import com.oocl.ha.merchant.vo.DishVO;
import com.oocl.ha.util.JSONUtil;
 

@Controller("mdc")
public class DishController {

	@Autowired
	private DishManager dm;
	@Autowired
	private JmsTemplate jmsTemplate;
	@Autowired
	@Qualifier("recommendedDishQueue")
	private Destination dishQuene;

	@RequestMapping("/addDish")
	//@ResponseBody
	public String addDish(String dname, String price, MultipartFile dicon, HttpServletRequest request) {

//		String token = request.getParameter("token");
//		String token_session = (String) request.getSession().getAttribute("token_session");
//		request.getSession().removeAttribute("token_session");
//		if (token_session == null||!token.equals(token_session)) {
//			return "redirect:/dishManager.html";
//		} else {
			HttpSession session = request.getSession();
			session.removeAttribute("icon");
			Double dPrice = Double.parseDouble(price);
			Dish dish = new Dish();
			dish.setDname(dname);
			dish.setPrice(dPrice);
			if (dicon.getSize()>0) {
				String iconName = UploadImgUtil.uploadImg(dicon);
				dish.setDicon(iconName);
			}
			int mId = (Integer) request.getSession().getAttribute("mId");
			dm.addDish(dish, mId);
			return "redirect:/dishManager.html";
//		}

	}

	@RequestMapping(value = "/loadAllDish", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String loadAllDish(HttpSession session) {
		Integer mId = (Integer) session.getAttribute("mId");

		String imgPrePath = ConfigUtil.getConfigValue("merchant.properties", "imagePath");
		String mdish = "";
		if (mId != null) {
			List<Dish> dList = dm.loadAllDish(mId);
			if (dList != null) {
				for (Dish d : dList) {
					d.setDicon(imgPrePath + d.getDicon());
				}
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("dList", dList);
				try {
					mdish = JSONUtil.objetc2Json(map);
				} catch (JsonProcessingException e) {
					e.printStackTrace();
				}
				return mdish;
			}
		}
		return mdish;
	}

	@RequestMapping("/recommendDish")
	@ResponseBody
	public String recommendDish(int dId, HttpSession session) {
		Integer mId = (Integer) session.getAttribute("mId");
		int m = dm.becomeRecommend(dId);
		if (m == 1) {
			Dish dish = dm.findById(dId);
			final DishVO dishVO = new DishVO();
			dishVO.setDicon(dish.getDicon());
			dishVO.setDid(dish.getDid());
			dishVO.setDname(dish.getDname());
			dishVO.setPrice(dish.getPrice());
			dishVO.setRecommend(dish.getRecommend());
			dishVO.setmId(dish.getMerchant().getMid());
			jmsTemplate.send(dishQuene, new MessageCreator() {
				public Message createMessage(Session session) throws JMSException {
					ObjectMapper mapper = new ObjectMapper();
					String json = new String();
					try {
						json = mapper.writeValueAsString(dishVO);
					} catch (JsonProcessingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					TextMessage om = session.createTextMessage(json);
					return om;
				}
			});
		}
		return dId + "";

	}

	@RequestMapping("/showImg")
	public void showImage(String img, HttpServletRequest request, HttpServletResponse response) throws Exception {
		OutputStream out = UploadImgUtil.showImage(img, request, response);
	}

	@RequestMapping("/deleteDish")
	@ResponseBody
	public String deleteDish(int dId) {
		int m = dm.deleteDish(dId);
		return "redirect:/loadAllDish";
	}

	@RequestMapping("/updateDish")
	public ModelAndView updateDish(int dId) {
		Dish dish = dm.findById(dId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dish", dish);
		ModelAndView mav = new ModelAndView("/updateDish", map);
		return mav;

	}

	@RequestMapping("/updateSelectDish")
	// @ResponseBody
	public String updateSelectDish(String dId, String dname, String price, MultipartFile dicon, HttpSession session) {
		Integer mId = (Integer) session.getAttribute("mId");
		Dish dish = new Dish();
		Merchant merchant = new Merchant();
		merchant.setMid(mId);
		dish.setMerchant(merchant);
		dish.setDid(Integer.parseInt(dId));
		dish.setDname(dname);
		dish.setPrice(Double.parseDouble(price));
		System.out.println(dicon.getSize() + "^^^^^^^^^^");
		if (dicon.getSize() > 0) {
			String iconName = UploadImgUtil.uploadImg(dicon);
			dish.setDicon(iconName);
		}
		int m = dm.updateDish(dish);
		return "redirect:/loadAllDish";
	}

	@RequestMapping("/undercarriage")
	@ResponseBody
	public String undercarriage(int dId) {
		int m = dm.undercarriage(dId);
		if (m == 1) {
			return dId + "";
		} else {
			return null;
		}
	}
//	@RequestMapping("/upload")
//	public String upload(Dish d) throws Exception{
//		System.out.println(d.getDname());
//		System.out.println(d.getDicon());
//		return "johnYu";
//	}
	@RequestMapping("/uploadi5")
	@ResponseBody
	public String uploadifive(@RequestParam(value ="Filedata", required = false) MultipartFile hw,HttpServletRequest request)
	throws Exception
	{

		System.out.println("==========upload==============");
		System.out.println("fileName:...."+hw.getOriginalFilename());
		InputStream in=hw.getInputStream();
		HttpSession session =request.getSession();
		session.setAttribute("icon", hw);
		
		System.out.println("avli...."+in.available());
		Enumeration<String> es1=	request.getParameterNames();
	while (es1.hasMoreElements()) {
		String s = (String) es1.nextElement();
		System.out.println(request.getParameter(s));
	}
		
		return "1";
	}
	@RequestMapping("/check")
	@ResponseBody
	public String check(HttpServletRequest request){
		Enumeration<String> es=	request.getHeaderNames();
		while (es.hasMoreElements()) {
			String s = (String) es.nextElement();
			System.out.println(s);
		}
	
		
		System.out.println("========================");
		Enumeration<String> es1=	request.getParameterNames();
	while (es1.hasMoreElements()) {
		String s = (String) es1.nextElement();
		System.out.println(s);
	}
		
		return "0";
	}
}
